package com.wb.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wb.reggie.common.R;
import com.wb.reggie.dto.DishDto;
import com.wb.reggie.entity.Category;
import com.wb.reggie.entity.Dish;
import com.wb.reggie.entity.DishFlavor;
import com.wb.reggie.service.CategoryService;
import com.wb.reggie.service.DishFlavorService;
import com.wb.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoInfo = new Page<>(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加模糊查询条件
        lambdaQueryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件（根据更新时间降序）
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //查询
        dishService.page(pageInfo,lambdaQueryWrapper);

        //拷贝  将pageInfo的内容拷贝到dishDtoInfo中，并忽略pageInfo中的records
        //忽略是因为要把records中的categoryId改成categoryName响应给前端，具体原因看博客第14章
        BeanUtils.copyProperties(pageInfo,dishDtoInfo,"records");
        List<Dish> records = pageInfo.getRecords();//对records内容改造
        List<DishDto> list = records.stream().map((item) -> {//item是Dish
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);//将item的属性拷贝到dishDto中
            Long categoryId =  item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);//通过categoryId查到分类的数据
            if(category != null){
                String categoryName = category.getName();//拿到分类名称
                dishDto.setCategoryName(categoryName);//赋值给dishDto
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoInfo.setRecords(list);
        return R.success(dishDtoInfo);
    }

    /**
     * 根据id查菜品信息 和 对应的口味信息
     * 注意，回显的并不是dish，除了菜品信息还有口味flavor信息，所以泛型是DishDto
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getOne(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> edit(@RequestBody DishDto dishDto){
        log.info("更新菜品：{}",dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("更新菜品成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
   /* @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //起售状态
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        return R.success(list);
    }*/

    /**
     * 还需要展示该菜品所对应的口味数据，需要对后端返回的值进行修改
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //起售状态
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        /**遍历查出来的list，将里面的数据拷贝到DishDto中，（由于DishDto继承了Dish，也有Dish里的所有属性）
         * 然后根据该菜品的id 查询口味表dishFlavor表中的对应口味信息，
         * 再将其口味信息封装到DishDto的List<DishFlavor> flavors中
         */
        List<DishDto> dishDtos = list.stream().map((item) -> {//每个item就是一个Dish
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            log.info("验证一下有没有拷贝进来，菜品价格：{}",dishDto.getPrice().toString());

            //设置dishDto里的categoryName
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId); //查分类表
            if(category != null){
                dishDto.setCategoryName(category.getName());
            }

            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            //SELECT * FROM dish_flavor WHERE dish_id = '1397849739276890114';
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtos);
    }
}
